package com.farmer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.farmer.mapper.GoodsMapper;
import com.farmer.mapper.UserMapper;
import com.farmer.pojo.Goods;
import com.farmer.pojo.Orders;
import com.farmer.pojo.User;
import com.farmer.service.OrdersService;
import com.farmer.mapper.OrdersMapper;
import com.farmer.utils.JwtHelper;
import com.farmer.utils.Result;
import com.farmer.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
* @author 86183
* @description 针对表【orders(订单信息表)】的数据库操作Service实现
* @createDate 2024-04-28 14:30:21
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public Result add(Orders orders)  {

        User user = userMapper.selectById(orders.getUserId());
        Goods goods = goodsMapper.selectById(orders.getGoodsId());
         orders.setPrice(goods.getPrice());
        //        判断用户余额是否足够
        if (user.getAccount() < orders.getPrice()) {
            return Result.build(null, ResultCodeEnum.NOT_SUFFICIENT_FUNDS);
        }
        String formattedDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        orders.setTime(DateFormat.getDateTimeInstance().format(new Date()));
        orders.setOrderId(formattedDate);
        ordersMapper.insert(orders);
//        购买成功，扣除用户余额
        user.setAccount(user.getAccount() - orders.getPrice());
        userMapper.updateById(user);
//        购买成功,修改库存
        if (!(ObjectUtils.isEmpty(goods))) {
            goods.setNum(goods.getNum() - 1);
            goods.setSales(goods.getSales()+1);
            goodsMapper.updateById(goods);
        }
        return Result.ok(null);
    }

    @Override
    public Result delete(Integer id) {
        ordersMapper.deleteById(id);
        return null;
    }


    @Override
    public Result update(Orders orders) {
        ordersMapper.updateById(orders);
        return Result.ok(null);
    }


    @Override
    public Result getById(Integer id) {
        Orders orders = ordersMapper.selectById(id);
        Goods goods = goodsMapper.selectById(orders.getGoodsId());
     if (goods!=null){
        orders.setImg(goods.getImg());
        orders.setGoodName(goods.getName());
     }
        User user = userMapper.selectById(orders.getUserId());
     if(user!=null) {
         orders.setUserName(user.getName());
     }
        if (orders != null) {
            return Result.build(orders, 111, "查询成功");
        } else {
            return Result.build(null, 101, "查询失败");
        }
    }

    @Override
    public Result getOrdersListByToken(String token) {
        // 验证token的有效性
        int userId = jwtHelper.getUserId(token).intValue();
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Orders::getUserId, userId);
        // 根据用户ID获取订单列表
        List<Orders> ordersList = ordersMapper.selectList(lambdaQueryWrapper);
        if (ordersList != null && !ordersList.isEmpty()) {
            for (Orders orders : ordersList) {
                Goods goods = goodsMapper.selectById(orders.getGoodsId());
                if (goods != null) {
                    orders.setImg(goods.getImg());
                    orders.setGoodName(goods.getName());
                }
                User user = userMapper.selectById(orders.getUserId());
                if (user != null) {
                    orders.setUserName(user.getName());
                }
            }
            return Result.build(ordersList, 111, "查询成功");
        } else {
            return Result.build(null, 101, "查询失败");
        }
    }


    //    public Result getAll() {
//        List<Orders> orders = ordersMapper.selectList(null);
//        if (orders != null && !orders.isEmpty()) {
//            return Result.build(orders, 111, "查询成功");
//        } else {
//            return Result.build(null, 101, "查询失败");
//        }
//    }
    @Override
    public Result getAll() {
        List<Orders> ordersList = ordersMapper.selectList(null);
        if (ordersList != null && !ordersList.isEmpty()) {
            for (Orders orders : ordersList) {
                Goods goods = goodsMapper.selectById(orders.getGoodsId());
                if (goods != null) {
                    orders.setImg(goods.getImg());
                    orders.setGoodName(goods.getName());
                }
                User user = userMapper.selectById(orders.getUserId());
                if (user != null) {
                    orders.setUserName(user.getName());
                }
            }
            return Result.build(ordersList, 111, "查询成功");
        } else {
            return Result.build(null, 101, "查询失败");
        }
    }


@Override
public Result getByOrderIdLike(String orderId) {
    // 构建查询条件
    LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    lambdaQueryWrapper.like(Orders::getOrderId, orderId);
    // 执行查询
    List<Orders> orders = ordersMapper.selectList(lambdaQueryWrapper);
    // 检查结果并丰富订单详情
    if (orders != null && !orders.isEmpty()) {
        for (Orders order : orders) {
            Goods goods = goodsMapper.selectById(order.getGoodsId());
            if (goods != null) {
                order.setImg(goods.getImg());
                order.setGoodName(goods.getName());
            }
            User user = userMapper.selectById(order.getUserId());
            if (user != null) {
                order.setUserName(user.getName());
            }
        }
        return Result.build(orders, 111, "查询成功");
    } else {
        return Result.build(null, 101, "未找到匹配信息");
    }
}


    /*
     * 分页查询*/
    @Override
    public Result page(Integer pageNum, Integer pageSize) {
        // 创建分页构造对象
        Page<Orders> page = new Page<>(pageNum, pageSize);
        // 执行分页查询
        IPage<Orders> result = ordersMapper.selectPage(page, null);
        if (result.getRecords() != null && !result.getRecords().isEmpty()) {
            for (Orders orders : result.getRecords()) {
                Goods goods = goodsMapper.selectById(orders.getGoodsId());
                if (goods != null) {
                    orders.setImg(goods.getImg());
                    orders.setGoodName(goods.getName());
                }
                User user = userMapper.selectById(orders.getUserId());
                if (user != null) {
                    orders.setUserName(user.getName());
                }
            }
            return Result.build(result, 111, "查询成功");
        }
        // 封装到统一响应体Result中
        return Result.ok(result);
    }




    /*
     * 发货方法*/
//    @Override
//    public Result shipOrder(Integer id) {
//        Orders order = ordersMapper.selectById(id);
//        if (order != null && order.getStatus().equals("待发货")) {
////            LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
////            lambdaQueryWrapper.eq(Orders::getOrderId, id);
//            order.setStatus("待收货");
//            ordersMapper.updateById(order);
//        }
//        return Result.ok(null);
//    }

    /*
    * 确认收货*/
//    @Override
//    public Result confirmReceipt(Integer id){
//        Orders order = ordersMapper.selectById(id);
//        if (order!=null &&order.getStatus().equals("待收货")){
//            order.setStatus("已完成");
////            LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
////            lambdaQueryWrapper.eq(Orders::getOrderId,id);
//            ordersMapper.updateById(order);
//        }
//        return Result.ok(null);
//    }
}




